import React, { forwardRef, useEffect, useImperativeHandle, useRef, useState } from 'react';

import {
  Button,
  DatePicker,
  Form,
  Input,
  Modal,
  Radio,
  Tag,
  Select,
  InputNumber,
  message,
  Row,
  Col,
  Checkbox,
} from 'antd';
import { modalLayoutLg, modalLayoutMd } from '@/config/layout';
import { request } from 'umi';
import GroupUserTreeSelectCom from '@/components/GroupUserTreeSelect'
const DictModal = (props: any, refs: any) => {
  const [form] = Form.useForm();
  const ChooseUserRef = useRef();
  // const [fileList,setfileList] = useState([]);
  const [measureClassData, setmeasureClassData] = useState([]);
  const { setFieldsValue, resetFields } = form;
  const [dataSource, setDataSource] = useState([]);
  const [templateList, settemplateList] = useState([]);
  const [groupLists, setgroupList] = useState([]);
  const [code, setCode] = useState('');
  const [isModalVisible, setIsModalVisible] = useState(false);
  const { TextArea } = Input;
  const messageTypeValue = Form.useWatch('message_type', form);
  const userListValue = Form.useWatch('userList', form);
  const groupListValue = Form.useWatch('groupListSelect', form);
  const [templateObj, settemplateObj] = useState({
    1: '',
    2: '',
    3: ''
  })
  useEffect(() => {
    console.log('messageTypeValue');
    console.log(messageTypeValue);
    if (messageTypeValue) {
      let newtem = { 1: '', 2: '', 3: '' }
      messageTypeValue.map((e, i) => {
        newtem[e] = templateObj[e];
      })
      settemplateObj(newtem);
    }

  }, [messageTypeValue])
  //显示弹窗
  const showModal = () => {
    setIsModalVisible(true);
  };

  //取消
  const handleCancel = () => {
    setIsModalVisible(false);
    setCode('');
    resetFields();
    settemplateObj({
      1: '',
      2: '',
      3: ''
    })
    props.callback && props.callback();
  };
  //确定
  const handleOk = () => {
    form
      .validateFields()
      .then((vals) => {
        let Obj = form.getFieldsValue();
        Obj = {
          ...Obj,
        };

        const url = code ? '/message/custom/edit' : '/message/custom/add';
        if (code) {
          Obj.id = code;
        } else {
        }
        let templateList = [];

        let groupListn = Obj.groupListSelect.map(item => {
          return { 'id': item }
        })
        for (let i in templateObj) {
          if (templateObj[i]) {
            templateList.push({
              id: templateObj[i]
            })
          }

        }
        Obj['templateList'] = templateList;
        Obj['groupList'] = groupListn;
        console.log(Obj);
        request(url, {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
          },
          data: Obj,
        }).then((res) => {
          message.success(res?.meta?.msg);
          setIsModalVisible(false);
          handleCancel();
        });
      })
      .catch((info) => { });
  };
  const getList = () => {
    request('/message/template/list', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      data: { "current": 1, "pageSize": 10000, "pageNo": 1, "templateType": '2' }
    }).then((res) => {
      settemplateList(res?.data?.data || []);
    });
  }

  const getGroupList = () => {
    request('/message/group/list', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      data: { "current": 1, "pageSize": 10000, "pageNo": 1 }
    }).then((res) => {
      setgroupList(res?.data?.data || [])
    });
  }
  const getDetail = (id: any) => {
    request('/message/custom/queryById?id=' + id, {
      method: 'GET',
      headers: {
        'Content-Type': 'application/json',
      },
      data: {
        id,
      },
    }).then((res) => {
      let templateList = res?.data?.templateList || [];
      let groupList = res?.data?.groupList || [];
      let grouplistv = groupList.map(item => item.id);
      console.log(grouplistv);
      let message_type = [];
      let templateObjn = { 1: '', 2: '', 3: '' };
      templateList.map((e, i) => {
        templateObjn[e.modeType] = e.id
        message_type.push(e.modeType);
      })
      setFieldsValue({
        ...res?.data,
        ...{
          message_type,
          groupListSelect: grouplistv
        }
      });
      settemplateObj(templateObjn);
      showModal();
    });
  };
  useImperativeHandle(refs, () => ({
    init: (id: any, record: any) => {
      if (id) {
        setCode(id);
        getDetail(id);
      } else {
        resetFields();
        showModal();
      }
      getList();
      getGroupList();
      // setfileList([]);
    },
  }));
  const renderTemDetail = (modeType) => {
    let arr = [];
    templateList.map((e, i) => {
      // return e.modeType == '2' ? <Option value={e.id} key={i}>{e.templateName}</Option> : <></>
      if (e.modeType == modeType && templateObj[modeType] == e.id) {
        arr.push(e.content)
      }
    })
    return arr;
  }
  const options = [
    { label: '邮件', value: '1' },
    { label: '手机短信', value: '2' },
    { label: '微信', value: '3' },
  ];
  return (
    <Modal
      title={code === '' ? '新增' : '编辑'}
      visible={isModalVisible}
      onOk={handleOk}
      onCancel={handleCancel}
      centered
      width={700}
      maskClosable={false}
      bodyStyle={{
        maxHeight: window.innerHeight - 150,
        overflowY: 'auto',
      }}
    >
      <Form form={form} {...modalLayoutMd}>
        <Form.Item
          label="自定义通知内容"
          name="messageContent"
          rules={[{ required: true, message: '请输入通知内容' }]}
        >
          <TextArea rows={4} />
        </Form.Item>
        <Form.Item
          label="选择消息组"
          name="groupListSelect"
          rules={[{ required: true, message: '请选择消息组' }]}
        >
          <Select mode="multiple" value={groupListValue} onChange={(value) => {

            setFieldsValue({
              ['groupListSelect']: value
            })
          }}>
            {
              groupLists.map((e, i) => {
                return <Option value={e.id} key={i}>{e.groupName}</Option>
              })
            }
          </Select>
        </Form.Item>
        <Form.Item
          label="选择消息类型"
          name="message_type"
          rules={[{ required: true, message: '请选择消息' }]}
        >
          <Checkbox.Group options={options} />
        </Form.Item>
        {
          messageTypeValue && messageTypeValue.indexOf('2') != -1 && <Form.Item
            label="选择短信模板"

            rules={[{ required: true, message: '选择短信模板' }]}
          >
            <Select value={templateObj['2']} onChange={(e) => settemplateObj({ ...templateObj, '2': e })}>
              {
                templateList.map((e, i) => {
                  return e.modeType == '2' ? <Option value={e.id} key={i}>{e.templateName}</Option> : <></>
                })
              }
            </Select>
            <div>{renderTemDetail(2)}</div>
          </Form.Item>
        }
        {
          messageTypeValue && messageTypeValue.indexOf('1') != -1 && <Form.Item
            label="选择邮件模板"

            rules={[{ required: true, message: '选择邮件模板' }]}
          >
            <Select value={templateObj['1']} onChange={(e) => settemplateObj({ ...templateObj, '1': e })}>
              {
                templateList.map((e, i) => {
                  return e.modeType == '1' ? <Option value={e.id} key={i}>{e.templateName}</Option> : <></>
                })
              }
            </Select>
            <div>{renderTemDetail(1)}</div>
          </Form.Item>
        }
        {
          messageTypeValue && messageTypeValue.indexOf('3') != -1 && <Form.Item
            label="选择微信模板"

            rules={[{ required: true, message: '选择微信模板' }]}
          >
            <Select value={templateObj['3']} onChange={(e) => settemplateObj({ ...templateObj, '3': e })}>
              {
                templateList.map((e, i) => {
                  return e.modeType == '3' ? <Option value={e.id} key={i}>{e.templateName}</Option> : <></>
                })
              }
            </Select>
            <div>{renderTemDetail(3)}</div>
          </Form.Item>
        }
      </Form>
      <GroupUserTreeSelectCom
        ref={ChooseUserRef}
        onOk={(checkedUsers) => {
          form.setFieldsValue({
            userList: checkedUsers
          })
        }}
      />
    </Modal>
  );
};
const AddMCom = forwardRef(DictModal);

export default AddMCom;
